<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API配置向导</title>
    <script src="./js/vue-mini2.6.14.js"></script>
    <script src="./js/axios.mini.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .login-section, .api-section {
            margin-bottom: 20px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, select, textarea, button {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            color: black;
            border: none;
            cursor: pointer;
            margin-right: 5px;
            margin-bottom: 5px;
        }
        button:hover {
            opacity: 0.8;
        }
        .method-selector {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }
        .method-selector select {
            width: 10%;
            margin-right: 0;
        }
        .url-input {
            width: 80%;
            min-width: 400px;
            margin-right: 0;
        }
        .method-selector button {
            width: 10%;
            min-width: 80px;
            background-color: #4CAF50;
        }
        .method-selector button:hover {
            background-color: #45a049;
        }
        .response-container {
            margin-top: 20px;
        }
        .view-toggle {
            margin-bottom: 10px;
        }
        .json-editor {
            width: 100%;
            min-height: 200px;
            font-family: monospace;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .error {
            color: red;
            margin-top: 10px;
        }
        .success {
            color: green;
            margin-top: 10px;
        }
        .quick-url-buttons {
            margin-bottom: 15px;
        }
        .get-button {
            background-color: #5dade2; /* 淡蓝色 */
        }
        .update-button {
            background-color: #f5b7b1; /* 淡粉色 */
        }
        .rebuild-button {
            background-color: #f5b7b1; /* 淡粉色 */
        }
        .button-comment {
            color: #666;
            font-size: 0.8em;
            margin-left: 5px;
        }
        .quick-url-buttons .gap{
            margin-left:40px
        }
        .quick-url-buttons .widA{
            width:130px
        }
        .quick-url-buttons .widB{
            width:300px
        }
    </style>
</head>
<body>AAA
<div id="app" class="container">
    AAA
    <!-- 登录部分 -->
    <div class="login-section" v-if="!isLoggedIn">
        <h2>用户登录</h2>
        <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" id="username" v-model="username" placeholder="请输入用户名">
        </div>
        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" v-model="password" placeholder="请输入密码">
        </div>
        <button @click="login">登录</button>
        <p class="error" v-if="loginError">{{ loginError }}</p>
    </div>

    <!-- API 请求部分 -->
    <div class="api-section" v-if="isLoggedIn">
        <h2>简易 Postman</h2>

        <!-- 快速录入URL按钮行 -->
        <div class="quick-url-buttons">
            <button class="get-button widA" @click="setUrl('/rtpack_config/list');setMethod('GET');clearShow()" title="获取rtpack_config表全部数据">config获取全部</button>
            <button class="update-button widA" @click="setUrl('/rtpack_config/batchUpdateByKey');setMethod('PUT');clearShow()" title="请求体没有的内容，不会修改也不会删除">config更新多条</button>

            <button class="get-button widA" @click="setUrl('/rtpack_config/by_key/portCommMoni');setMethod('GET');clearShow()" title="获取rtpack_config中的portCommMoni">config获取端口</button>
            <button class="get-button widA" @click="setUrl('/rtpack_config/by_key/try_times_fail');setMethod('GET');clearShow()" title="获取rtpack_config中的portCommMoni">config获取次数</button>
            <button class="update-button widA" @click="setUrl('/rtpack_config/updateByKey');setMethod('PUT');clearShow()" title="以key为主键更新rtpack_config中单条记录">config更新单条</button>


            <br>


            <button class="get-button widA" @click="setUrl('/rtpack_moniip/list');setMethod('GET');clearShow()" title="获取rtpack_moniip表全部数据">moniip获取全部</button>
            <button class="update-button widA" @click="setUrl('/rtpack_moniip/batchUpdateByIndex');setMethod('PUT');clearShow()" title="请求体没有的内容，不会修改也不会删除">moniip更新多条</button>
            <button class="rebuild-button widA" @click="setUrl('/rtpack_moniip/replaceAll');setMethod('POST');clearShow()" title="删除表后重新插入，即请求体没有的内容会被删除">moniip重建表</button>
            <button class="get-button widA" @click="setUrl('/rtpack_moniip/by_index/0');setMethod('GET');clearShow()" title="获取rtpack_moniip单条记录，index/0其中0可以调整为其他索引值">moniip获取单条</button>
            <button class="update-button widA" @click="setUrl('/rtpack_moniip/updateByIndex');setMethod('PUT');clearShow()" title="以index为主键更新rtpack_moniip中单条记录">moniip更新单条</button>

            <br>

            <button class="get-button widA" @click="setUrl('/rtpack_hostname/list');setMethod('GET');clearShow()" title="获取rtpack_hostname表全部数据">hostname获取全部</button>
            <button class="update-button widA" @click="setUrl('/rtpack_hostname/batchUpdateByIndex');setMethod('PUT');clearShow()" title="请求体没有的内容，不会修改也不会删除">hostname更新多条</button>
            <button class="rebuild-button widA" @click="setUrl('/rtpack_hostname/replaceAll');setMethod('POST');clearShow()" title="删除表后重新插入，即请求体没有的内容会被删除">hostname重建表</button>
            <button class="get-button widA" @click="setUrl('/rtpack_hostname/by_index/0');setMethod('GET');clearShow()" title="获取rtpack_hostname单条记录，index/0其中0可以调整为其他索引值">hostname获取单条</button>
            <button class="update-button " @click="setUrl('/rtpack_hostname/updateByIndex');setMethod('PUT');clearShow()" title="以index为主键更新rtpack_hostname中单条记录">hostname更新单条</button>

        </div>

        <div class="method-selector">
            <select v-model="selectedMethod">
                <option value="GET">GET</option>
                <option value="POST">POST</option>
                <option value="PUT">PUT</option>
            </select>
            <!-- 修改后的URL选择/输入框 -->
            <input
                    type="text"
                    v-model="selectedUrl"
                    class="url-input"
                    list="urlOptions"
                    placeholder="输入或选择URL">
            <datalist id="urlOptions">
                <option v-for="(url, index) in presetUrls" :value="url" :key="index">{{ url }}</option>
            </datalist>
            <button @click="sendRequest">发送请求</button>
        </div>

        <div class="status-info">
            <p>状态码: {{ responseStatus }}</p>
            <p class="success" v-if="requestSuccess">请求成功!</p>
            <p class="error" v-if="requestError">{{ requestError }}</p>
        </div>

        <div class="form-group" v-if="selectedMethod !== 'GET'">
            <label>请求体 (JSON)</label>
            <button @click="copyResponseToRequestBody" style="margin-left: 10px; background-color: #5dade2;">从响应体复制文本至此处</button>
            <textarea class="json-editor" v-model="requestBody" placeholder='例如: { "key": "value" }'></textarea>
        </div>

        <div class="response-container">
            <h3>响应</h3>
            <div class="view-toggle">
                <button @click="toggleViewMode">{{ viewMode === 'json' ? '切换为表格视图' : '切换为JSON视图' }}</button>
            </div>

            <div v-if="viewMode === 'json'">
                <textarea class="json-editor" v-model="responseData"></textarea>
            </div>

            <div v-else>
                <template v-if="isValidJson && Array.isArray(resultData)">
                    <table>
                        <thead>
                        <tr>
                            <th v-for="(value, key) in resultData[0]" :key="key">{{ key }}</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr v-for="(item, index) in resultData" :key="index">
                            <td v-for="(value, key) in item" :key="key">
                                <input type="text" v-model="item[key]" @change="updateResponseJson">
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </template>

                <template v-else-if="isValidJson && typeof resultData === 'object' && !Array.isArray(resultData)">
                    <table>
                        <thead>
                        <tr>
                            <th>键</th>
                            <th>值</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr v-for="(value, key) in resultData" :key="key">
                            <td>{{ key }}</td>
                            <td>
                                <input type="text" v-model="resultData[key]" @change="updateResponseJson">
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </template>

                <div v-else class="error">无法转换为表格视图</div>
            </div>


        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            username: '',
            password: '',
            isLoggedIn: false,
            loginError: '',

            selectedMethod: 'GET',
            selectedUrl: '/rtpack_moniip/list',
            presetUrls: [
                '/rtpack_config/list',
                '/rtpack_moniip/list',
                '/rtpack_hostname/list'
            ],

            requestBody: '',
            responseData: '',
            responseStatus: '',
            requestSuccess: false,
            requestError: '',

            viewMode: 'json',
            parsedResponse: null,
            isValidJson: false,
            resultData: null
        },
        methods: {
            // 设置URL的方法
            setUrl(endpoint) {
                this.selectedUrl = endpoint;
                // 根据端点自动设置方法
                if (endpoint.includes('get')) {
                    this.selectedMethod = 'GET';
                } else if (endpoint.includes('update') || endpoint.includes('rebuild')) {
                    this.selectedMethod = 'POST'; // 或 PUT，根据您的API设计
                }
            },
            setMethod(metd){
                this.selectedMethod = metd
            },
            clearShow(){
                this.responseStatus = "";
                this.requestSuccess = false;
                this.requestError = "";
            },
            async login() {
                // 清空错误信息
                this.loginError = '';

                // 验证输入
                if (!this.username || !this.password) {
                    this.loginError = '请输入用户名和密码';
                    this.focusPassword();
                    return;
                }

                try {
                    const response = await axios.post('/wall/try_passing', {
                        uid: this.username,
                        unk: this.password
                    }, {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    console.log(response);
                    // 检查响应结果
                    if (response.data.msg === 'success') {
                        // 登录成功
                        this.isLoggedIn = true;
                    } else {
                        // 登录失败
                        this.loginError = '用户名或密码错误';
                        this.focusPassword();
                    }

                } catch (error) {
                    console.error('登录请求失败:', error);
                    this.loginError = '登录请求失败，请稍后再试';
                    this.focusPassword();

                    // 可以根据不同的错误状态码显示不同的提示
                    if (error.response) {
                        switch (error.response.status) {
                            case 400:
                                this.loginError = '请求参数错误';
                                break;
                            case 401:
                                this.loginError = '用户名或密码错误';
                                break;
                            case 500:
                                this.loginError = '服务器错误，请稍后再试';
                                break;
                        }
                    }
                }
            },

            // 聚焦密码输入框并选中内容
            focusPassword() {
                this.$nextTick(() => {
                    const passwordInput = document.getElementById('password');
                    if (passwordInput) {
                        passwordInput.focus();
                        passwordInput.select();
                    }
                });
            },


            async sendRequest() {
                this.requestSuccess = false;
                this.requestError = '';

                const url = this.selectedUrl;

                if (!url) {
                    this.requestError = '请输入URL';
                    return;
                }

                try {
                    let options = {
                        method: this.selectedMethod,
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    };

                    if (this.selectedMethod !== 'GET') {
                        if (this.requestBody) {
                            try {
                                JSON.parse(this.requestBody);
                                options.body = this.requestBody;
                            } catch (e) {
                                this.requestError = '请求体不是有效的JSON';
                                return;
                            }
                        } else {
                            this.requestError = '请提供请求体';
                            return;
                        }
                    }

                    const response = await fetch(url, options);
                    this.responseStatus = response.status;

                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    let fullRes = await response.json();
                    const data = fullRes.result;
                    this.responseData = JSON.stringify(data, null, 2);
                    this.parseResponseData();
                    this.requestSuccess = true;

                } catch (error) {
                    this.requestError = `请求失败: ${error.msg}`;
                    this.responseData = '';
                    this.responseStatus = '';
                }
            },

            toggleViewMode() {
                this.viewMode = this.viewMode === 'json' ? 'table' : 'json';
            },

            parseResponseData() {
                try {
                    const parsedData = JSON.parse(this.responseData);
                    // 提取result，如果没有result则使用整个响应数据
                    this.resultData = parsedData.result || parsedData;
                    this.isValidJson = true;
                } catch (e) {
                    this.isValidJson = false;
                    this.resultData = null;
                }
            },
            updateResponseJson() {
                // 如果是从resultData修改，需要重新构建完整的响应数据
                if (this.resultData) {
                    const originalData = JSON.parse(this.responseData);
                    if (originalData.result) {
                        originalData.result = this.resultData;
                    } else {
                        Object.assign(originalData, this.resultData);
                    }
                    this.responseData = JSON.stringify(originalData, null, 2);
                } else {
                    this.responseData = JSON.stringify(this.parsedResponse, null, 2);
                }
            },
            copyResponseToRequestBody() {
                if (this.responseData) {
                    try {
                        // 尝试解析JSON并重新格式化，确保是有效的JSON
                        const parsed = JSON.parse(this.responseData);
                        this.requestBody = JSON.stringify(parsed, null, 2);
                    } catch (e) {
                        // 如果不是有效的JSON，直接复制原始文本
                        this.requestBody = this.responseData;
                    }
                } else {
                    alert('响应体为空，无法复制');
                }
            }
        },
        watch: {
            responseData(newVal) {
                this.parseResponseData();
            }
        },
        created() {
            console.log("created")
        }
    });
</script>
</body>
</html>